# import win32api
# import win32con
# import win32gui
# import win32ui
import os
import threading
import time
import allure
import pyautogui
from PIL import Image

from common.log.log import log
from config.conf import FAIL_IMAGE_DIR

flag = False  # 停止标志位


@allure.step('创建或清空目录')
def clear_dir(path):
    # 创建或清空目录
    log.info(os.path.isdir(path))
    if not os.path.isdir(path):
        os.makedirs(path)  # 创建目录
    else:  # 清空目录
        [os.remove(os.path.join(path, file_name)) for file_name in os.listdir(path)]


def del_files(path):
    """
    删除指定目录下的所有文件
    """
    try:
        if os.path.isdir(path):
            ls = os.listdir(path)
            for i in ls:
                c_path = os.path.join(path, i)
                if os.path.isdir(c_path):  # 如果是文件夹那么递归调用一下
                    del_files(c_path)
                else:  # 如果是一个文件那么直接删除
                    os.remove(c_path)
            log.info('文件已经清空完成！！！')
    except Exception as e:
        log.error(f'删除指定目录下的所有文件出现异常为：{e}')
        raise e


@allure.step('循环截图函数')
def shot(img_dir):
    # 循环截图函数
    i = 0
    time.sleep(3)
    while True:
        i += 1
        img_file = os.path.join(img_dir, f'{i}.jpg')
        time.sleep(1)
        # 调用第三方插件截图，该截图为当前屏幕的截图，Chrome如果被其他应用挡住，则看不到，需优化成：shot_chrome
        im = pyautogui.screenshot()
        im.save(img_file)
        if flag:
            log.info("截图结束！")
            break


@allure.step('循环截图函数')
def shot_chrome(img_dir, drive):
    # 循环截图函数
    i = 0
    time.sleep(3)
    while True:
        i += 1
        img_file = os.path.join(img_dir, f'{i}.jpg')
        time.sleep(0.1)
        # 调用Chrome如自带截图，屏幕挡住也能看到
        drive.save_screenshot(img_file)
        if flag:
            log.info("截图结束！")
            break


@allure.step('截图启停功能')
def shot_flag(key=0):
    global flag
    if key == 1:
        flag = True
        log.info("停止截图！")
        return False
    elif key == 0:
        flag = False
        log.info('启动截图')


# @allure.step('PC截图功能')
# def pc_shots():
#     """
#     PC截图功能
#     :return:
#     """
#     hwnd = 0
#     hwndDC = win32gui.GetWindowDC(hwnd)
#     mfcDC = win32ui.CreateDCFromHandle(hwndDC)
#     saveDC = mfcDC.CreateCompatibleDC()
#     saveBitMap = win32ui.CreateBitmap()
#     MoniterDev = win32api.EnumDisplayMonitors(None, None)
#     w = MoniterDev[0][2][2]
#     h = MoniterDev[0][2][3]
#     saveBitMap.CreateCompatibleBitmap(mfcDC, w, h)
#     saveDC.SelectObject(saveBitMap)
#     saveDC.BitBlt((0, 0), (w, h), mfcDC, (0, 0), win32con.SRCCOPY)
#     nowTime = time.strftime('%Y%m%d%H%M%S')
#     dayTime = time.strftime('%Y%m%d')
#     # path = f'..\\log\image\\{dayTime}\\'
#     path = FAIL_IMAGE_DIR + f'/{dayTime}/'
#     if not os.path.exists(path):
#         os.makedirs(path)
#     filename = path + nowTime + '.jpg'
#     saveBitMap.SaveBitmapFile(saveDC, filename)
#     with open(filename, "rb") as f:
#         bin_contents = f.read()
#     return bin_contents


@allure.step('失败截图')
def shots():
    """
    失败截图
    """
    nowTime = time.strftime('%Y%m%d%H%M%S')
    dayTime = time.strftime('%Y%m%d')
    path = FAIL_IMAGE_DIR + f'\\{dayTime}\\'
    if not os.path.exists(path):
        os.makedirs(path)
    img_file = path + nowTime + '.jpg'
    im = pyautogui.screenshot()
    im.save(img_file)
    log.info("截图")
    with open(img_file, "rb") as f:
        bin_contents = f.read()
    return bin_contents


if __name__ == '__main__':
    print("1")
    # shots()
    # pc_shots()
    # img_dir = "D:\\autowork\\log\\img"  # 临时图片目录
    # gif_file = "D:\\autowork\\log\\gif"  # 临时gif文件
    # print(img_dir)
    # clear_dir(img_dir)  # 清空目录
    # clear_dir(gif_file)  # 清空目录
    # t = threading.Thread(target=shot, args=(img_dir,))  # 新建线程
    # t.start()  # 启动截图线程

    # time.sleep(20)
    # # stop_shot(1)
    # # 图片拼接成gif
    # img_list = os.listdir(img_dir)  # 列出目录所有图片
    # img_list.sort(key=lambda x: int(x[:-4]))  # 排序
    #
    # print(img_list)
    # # sum_img = ceil(len(img_list) / 50)      # 50张截图拼接一次
    # sum = len(img_list)
    #
    # # for i in range(sum_img):
    # if sum <= 100:
    #     first_img = Image.open(os.path.join(img_dir, img_list[0]))  # 第一张图片对象
    #     else_imgs = [Image.open(os.path.join(img_dir, img)) for img in img_list[1:]]  # 剩余图片对象
    #     first_img.save(gif_file + '\\record.gif', append_images=else_imgs,
    #                    duration=100,  # 每张图片的过过渡时间
    #                    save_all=True)  # 拼接保存，如果想要循环播放可以加上loop=0
    #     log.info('拼接gif完成！')
    # else:
    #     start_num = sum - 100
    #     in_num = sum - 99
    #     # end_num = 50
    #     print(f'第一张为{start_num}')
    #     first_img = Image.open(os.path.join(img_dir, img_list[start_num]))  # 第一张图片对象
    #     else_imgs = [Image.open(os.path.join(img_dir, img)) for img in img_list[in_num:]]  # 剩余图片对象
    #     first_img.save(gif_file + f'\\record.gif', append_images=else_imgs,
    #                    duration=100,  # 每张图片的过过渡时间
    #                    save_all=True)  # 拼接保存，如果想要循环播放可以加上loop=0
    #     log.info('拼接gif完成！')
    #     # start_num += 50
    #     # in_num += 50
    #     # end_num += 50
    #     # time.sleep(1)
    #
    # # gif_list = os.listdir(gif_file)  # 列出目录所有gif
    # # # gif_list.sort(key=lambda x: int(x[:-4]))  # 排序
    # # print(gif_list)
    # # for i in range(len(gif_list)):
    # #     print(gif_file + gif_list[i])
    # with open(gif_file + '\\record.gif', "rb") as f:
    #     allure.attach(f.read(), name=f"屏幕截图拼接gif图", attachment_type=allure.attachment_type.GIF)
